package leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-11-08 13:56
 **/
public class LeetCode105 {

    Map<Integer, Integer> map = new HashMap<>();

    private TreeNode myBuildTree(int[] preorder, int[] inorder, int preLeft, int preRight, int inLeft, int inRight) {
        if (preLeft > preRight) {
            return null;
        }
        //根节点在中序数组中的位置
        int inRoot = map.get(preorder[preLeft]);
        //构建节点
        TreeNode root = new TreeNode(inorder[inRoot]);
        //左子树长度
        int llen = inRoot - inLeft;
        //递归构建左子树
        root.left = myBuildTree(preorder, inorder, preLeft + 1, preLeft + llen, inLeft, inRoot - 1);
        //递归构建右子树
        root.right = myBuildTree(preorder, inorder, preLeft + llen + 1, preRight, inRoot + 1, inRight);

        //返回根节点
        return root;
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int n = inorder.length;
        //将中序的数组放到map中，便于寻找根节点的下标。
        for (int i = 0; i < n; i++) {
            map.put(inorder[i], i);
        }
        return myBuildTree(preorder, inorder, 0, n - 1, 0, n - 1);
    }

}
